package com.pphh.demo;

import com.pphh.demo.strategy.ShardStrategy;
import groovy.lang.GroovyClassLoader;

import java.io.File;
import java.net.URL;

/**
 * use Class.forName to load groovy class dynamically
 *
 * @author huangyinhuang
 * @date 9/25/2018
 */
public class DynamicClassLoader {

    public static void main(String[] args) throws Exception {
        ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
        GroovyClassLoader loader = new GroovyClassLoader(systemClassLoader);

        URL url = DynamicGroovyStrategy.class.getClassLoader().getResource("TestShardStrategy.groovy");
        File file = new File(url.getFile());
        loader.parseClass(file);

        // load by class.forName
        Class clazz = Class.forName("groovy.TestShardStrategy", true, loader);

        ShardStrategy shardStrategy = (ShardStrategy) clazz.newInstance();
        String dbShard = shardStrategy.calculateDbShard(200L);
        String tableShard = shardStrategy.calculateTableShard(200L);
        System.out.println(String.format("db = %s, table = %s", dbShard, tableShard));
    }
}
